import showroomData from "../../../stands/showroomSelect/js/showroomData";
import tiyData from "./chat_message_detail_data";

/**
 * 初始化
 * @param self
 * @param tiyData
 */
export const init = (self, tiyData) => {
  tiyData.tPage.total = 1;
  tiyData.tPage.startIndex = 0;
  tiyData.tPage.stepNumber = 30;
  tiyData.tPage.currentPage = 1;

};


export const getTabList=(self, tiyData)=>{
  tiyData.tData.tabList.splice(0,tiyData.tData.tabList.length);
  let param = {
    "type": 2
  };

  self.$apiOther.queryManageTabs(param).then(function (response) {
    if(response.success){
      response.result.forEach(function(item){
        tiyData.tData.tabList.push(item);
      })
    }else{
      self.$Message.error(response.errorMessage);
    }
  });
}

/**
 * 从服务器请求列表
 * @param self
 * @param tiyData
 * @param toBottom是否滚动到最底部
 * @param direction 'up'上翻，'down'下翻
 * @returns {Array}
 */
export const webList = (self, tiyData,toBottom,direction) => {
  // self.$Spin.show();
  self.isLoading = direction!="up";
  if(direction!="up"){
    tiyData.tPage.startIndex = 0;
  }else{
    tiyData.tPage.startIndex = tiyData.tData.messageList.length;
  }

  let div = document.getElementById('chat_content');
  let scrollTop = div.scrollTop;//数据加载之前滚动条位置

  self.$apiChat.chatMessageDetail({
    "pageSize": tiyData.tPage.stepNumber,
    "startIndex": tiyData.tPage.startIndex,
    "userId":self.userId
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      let messagePage = response.result;
      if(messagePage.list.length>0 && messagePage.list[0].userId!=self.userId){
        return;
      }

      if(direction=="up"){//上翻
        messagePage.list.forEach(
          function (item) {
            //判断前5条是否重复
            let flag = true;
            for(let index = 0; index < 5; index++){
              if(index == tiyData.tData.messageList.length){
                break;
              }
              if(tiyData.tData.messageList[index].id == item.id){
                flag = false;
                break;
              };
            }

            if(flag){
              if(item.type!=100 && item.type!=200 && item.type!= 600){
                item.content = self.$toJson(item.content);
              }
              tiyData.tData.messageList.unshift(item);
            }
          }
        );
        let size = messagePage.list.length;
        if(size==0){
          self.hasPre = false;
        }
        if(size>0 && tiyData.tData.messageList.length>size){
          self.$nextTick(() => {
            let div = document.getElementById('chat_content');
            div.scrollTop = document.getElementsByClassName("chat_base_content")[size].offsetTop-50;
          })
        }
        self.preLoading = false;
        self.showLoadingPre = true;

      }
      else {//下翻
        let newArray = new Array();
        for(let i=0;i<messagePage.list.length;i++){
          //判断是否已加载+是否已设置为已读
          let item = messagePage.list[i];
          let index = tiyData.tData.messageList.findIndex((value)=>{
            return item.id ==value.id }
          );
          if(index==-1){
            newArray.push(item);
            continue;
          } else if(tiyData.tData.messageList[index].readed != item.readed || tiyData.tData.messageList[index].state != item.state){
            //如果已存在该消息判断是否状态改变+消息状态发送变化
            //直接赋值，避免根据type对content进行转换
            tiyData.tData.messageList[index].state = item.state;
            tiyData.tData.messageList[index].readed = item.readed;
            tiyData.tData.messageList.splice(index,1,tiyData.tData.messageList[index]);
          }
        }

        if(newArray.length > 0){
          newArray.reverse().forEach(
            function (item) {
              if(item.type!=100 && item.type!=200 && item.type!=600){
                item.content = self.$toJson(item.content);
              }
              if(item.sourceType != null){
                item.sourcePage = convertSourceType(item.sourceType, item.deviceType);
                  item.sourceValue = self.$toJson(item.sourceValue);
              }
              tiyData.tData.messageList.push(item);
            }
          );

          self.$nextTick(function () {
            let div = document.getElementById('chat_content');
            if((div.scrollHeight-div.scrollTop-div.clientHeight)>25){
              self.showMessageNotice = true;
            };
          });
        }

        self.isLoading = false;
        if(toBottom){
          self.scrollToBottom();//滚动条到最底部
        }else{//当前位置不变
          self.$nextTick(() => {
            let contentDiv = document.getElementById('chat_content');
            contentDiv.scrollTop = scrollTop;
          })
        }
      }
    } else {
      self.$Message.error(response.errorMessage);
      self.preLoading = false;
      self.showLoadingPre = true;
      //防止抛出异常进入死循环h
      // self.refreshTime = 60;
      // self.isLoading = false;
    }
    self.refreshTime = 60;
    self.isLoading = false;
  }).catch(function (error) {
    self.$Message.error("查询失败，请稍后再试");
    self.preLoading = false;
    self.showLoadingPre = true;
    //防止抛出异常进入死循环
    self.refreshTime = 60;
    self.isLoading = false;
  }.bind(this));
};


/**
 * 发送消息推送
 * @param self
 * @param tiyData
 */
export const chatSendMessage = (self, tiyData) => {

  if(tiyData.tParams.messageSendParam.picUrl!="" && tiyData.tParams.messageSendParam.content!=""){
    self.$Message.error("无法同时推送图片和文本")
    return;
  }
  if(tiyData.tParams.messageSendParam.picUrl=="" && tiyData.tParams.messageSendParam.content==""){
    self.$Message.error("请输入推送内容")
    return;
  }
  if(tiyData.tParams.messageSendParam.type==600){
    var regex = /^http(s)?:\/\/([\S-]+\.)+[\S-]+(\/[\S- ./?%&=]*)?$/;
    if(!regex.test(tiyData.tParams.messageSendParam.content)){
      self.$Message.error("请输入正确的超链接地址")
      return;
    }

  }
  if(tiyData.tParams.messageSendParam.type!=100){
    self.$Spin.show();
  }
  self.disableSendButton = true;//禁用发送按钮
  self.$apiChat.chatSendMessage({
    userId:self.userId,
    title:"",
    picUrl:tiyData.tParams.messageSendParam.content==""?self.yunPath+tiyData.tParams.messageSendParam.picUrl:"",
    content:tiyData.tParams.messageSendParam.content,
    type:tiyData.tParams.messageSendParam.type
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      tiyData.tStatus.modalMessage.isShow = false;
      if(tiyData.tParams.messageSendParam.type==100){
        self.textData = '';
      }
      tiyData.tParams.messageSendParam.content = '';
      tiyData.tParams.messageSendParam.picUrl = "";
      self.search(true);
      self.disableSendButton = false;//禁用发送按钮
    } else {
      tiyData.tParams.messageSendParam.content = '';
      tiyData.tParams.messageSendParam.picUrl = "";
      self.disableSendButton = false;//禁用发送按钮
      self.$Message.error(response.errorMessage);
    }
  });

};


export const getMessageUserInfo = (self, tiyData) => {
  self.$Spin.show();
  self.$apiChat.getMessageUserInfo({
    userId:self.userId,
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      let result = response.result;
      tiyData.tData.messageUserInfo.country = result.country;
      tiyData.tData.messageUserInfo.version = result.version;
      tiyData.tData.messageUserInfo.deviceType = result.device_type;
      tiyData.tData.messageUserInfo.orderCount= result.orderCount;
      tiyData.tData.messageUserInfo.registertime= result.registertime;
      tiyData.tData.messageUserInfo.registerType= result.third_party;
      tiyData.tData.messageUserInfo.userName= result.full_name;
      tiyData.tData.messageUserInfo.userCode= result.encodeName;
      tiyData.tData.messageUserInfo.cartCount= result.cartCount;
      tiyData.tData.messageUserInfo.tabId=result.tabId;
      // if(result.userNote){
      //   tiyData.tData.messageUserInfo.userNote= result.userNote;
      // }else{
      //   tiyData.tData.messageUserInfo.userNote= "";
      // }
      tiyData.tData.messageUserInfo.email=result.email;
    } else {
      self.$Message.error(response.errorMessage);
    }
  });

};

/**
 * 删除已经上传的消息图片（只能删除未发送的消息图片）
 * @param self
 * @param tiyData
 */
export const deleteMessagePic = (self, tiyData) => {
  self.$Spin.show();
  self.$apiChat.deleteMessagePic({ "picUrl": tiyData.tParams.messageSendParam.picUrl }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      tiyData.tParams.messageSendParam.picUrl = '';
    } else {
      self.$Message.error("移除图片失败！" + response.errorMessage);
    }
  });
};

/**
 * 查询产品
 * @param self
 * @param tiyData
 */
export const searchProduct = (self, tiyData) => {
  self.$Spin.show();
  let data = {
    pageSize: tiyData.searchInfoPage.stepNumber,
    pageNum: tiyData.searchInfoPage.currentPage,
    productCode: tiyData.tParams.searchInfoParam.productCode
  };
  self.$ySpliceAll(tiyData.tData.productList);
  self.$apiProduct.getProductList(data).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      tiyData.searchInfoPage.total = response.result.total;
      tiyData.searchInfoPage.stepNumber = response.result.pageSize;
      let products = response.result.list;
      products.forEach(
        function (item) {
          tiyData.tData.productList.push(item);
        }
      );
    } else {
      self.$Message.error("查询产品失败！" + response.errorMessage);
    }
  });
}

/**
 * 查询订单
 * @param self
 * @param tiyData
 */
export const searchOrder = (self, tiyData) => {
  self.$Spin.show();
  let data = {
    pageSize: tiyData.searchInfoPage.stepNumber,
    pageNum: tiyData.searchInfoPage.currentPage,
    userId : tiyData.tParams.searchInfoParam.userId,
    serialNumber : tiyData.tParams.searchInfoParam.serialNumber,
    withManageInfo: false
  };
  self.$ySpliceAll(tiyData.tData.orderList);
  self.$apiOrder.orderList(data).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      tiyData.searchInfoPage.total = response.result.total;
      tiyData.searchInfoPage.stepNumber = response.result.pageSize;
      let products = response.result.list;
      products.forEach(
        function (item) {
          tiyData.tData.orderList.push(item);
        }
      );
    } else {
      self.$Message.error("查询订单失败！" + response.errorMessage);
    }
  });
};

/**
 * 从服务器请求购物车列表
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const searchCart = (self, tiyData) => {
  self.$Spin.show();
  tiyData.tData.cartPriceCount = 0;
  tiyData.tData.cartWeightCount = 0;
  let data = {
    pageSize: tiyData.searchInfoPage.stepNumber,
    pageNum: tiyData.searchInfoPage.currentPage,
    userId : tiyData.tParams.searchInfoParam.userId
  };
  self.$ySpliceAll(tiyData.tData.cartList);
  self.$apiUser.getShoppingCart(data).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      tiyData.searchInfoPage.total = response.result.data.total;
      tiyData.searchInfoPage.stepNumber = response.result.data.pageSize;
      let cartList = response.result.data.list;
      cartList.forEach(
        function (item) {
          tiyData.tData.cartList.push(item);
        }
      );
      tiyData.tData.cartWeightCount = response.result.sumWeight + 'g';
      tiyData.tData.cartPriceCount = '$' + response.result.sumPrice.toFixed(2);
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 查询用户登录记录
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const searchRecord = (self, tiyData) => {
  self.$Spin.show();
  let data = {
    pageSize: tiyData.searchInfoPage.stepNumber,
    pageNum: tiyData.searchInfoPage.currentPage,
    userId : tiyData.tParams.searchInfoParam.userId
  };
  self.$ySpliceAll(tiyData.tData.recordList);
  self.$apiUser.getLoginRecords(data).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      let recordPage = response.result;
      tiyData.searchInfoPage.total = response.result.total;
      tiyData.searchInfoPage.stepNumber = response.result.pageSize;
      recordPage.list.forEach(
        function (item) {
          tiyData.tData.recordList.push(item);
        }
      );
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 消息来源页面类型转为文本
 * @param sourceType
 * @param device
 * @returns {string}
 */
function convertSourceType(sourceType, device){
  let sourcePage = "";
  switch(sourceType){
    // case 10:
    //   if(device == 3){
    //     sourcePage = "首页";
    //   } else {
    //     sourcePage = "app右上角图标";
    //   }
    // break;
    case 31:
    case 32:
      sourcePage = "产品";
      break;
    // case 40:
    case 41:
    case 42: //订单售后先按订单处理
      sourcePage = "订单";
      break;
    default:
      break;
  }
  return sourcePage;
}

/**查询会话状态*/
export const getMessageStatus = (self, tiyData) => {
  let params = {userId: self.userId};
  tiyData.tData.messageStatus = {};
  self.$Spin.show();
  //初始化tagList
  self.selectedTags.splice(0);
  self.tagList.splice(0);
  self.tagList.push(...tiyData.tData.tagList);
  self.$apiChat.queryMessageStatus(params).then(response => {
    if(response.success) {
      if(response.result!=null) {
        tiyData.tData.messageStatus = response.result;
        if(tiyData.tData.messageStatus.tags!=null && tiyData.tData.messageStatus.tags!='') {
          self.selectedTags = self.$toJson(tiyData.tData.messageStatus.tags);
          for(let selectedTag of self.selectedTags) {
            let hasTag = false;
            for(let tag of self.tagList) {
              if(selectedTag==tag.value) {
                hasTag = true;
              }
            }
            if(!hasTag) {
              self.tagList.push({value: selectedTag, label: selectedTag});
            }
          }
        }
      }
    }else{
      self.$Message.error(response.errorMessage);
    }
    self.$Spin.hide();
  });
}

/**更新会话标签*/
export const updateStatusTags = (self, tiyData) => {
  let params = {
    userId: self.userId,
    tags: tiyData.tData.messageStatus.tags,
  };
  self.$Spin.show();
  self.$apiChat.updateStatusTags(params).then(response => {
    self.$Spin.hide();
    if(response.success) {
      self.$Message.success("标签保存成功!");
      getMessageStatus(self, tiyData);
      self.$parent.webList();
    }else{
      self.$Message.error(response.errorMessage);
    }
  });
}

/**更新会话备注*/
export const updateStatusNote = (self, tiyData) => {
  let params = {
    userId: self.userId,
    note: tiyData.tParams.noteParam,
  };
  self.$Spin.show();
  self.$apiChat.updateStatusNote(params).then(response => {
    self.$Spin.hide();
    if(response.success) {
      self.$Message.success("备注保存成功!");
      getMessageStatus(self, tiyData);
      self.$parent.webList();
    }else{
      self.$Message.error(response.errorMessage);
    }
  });
}

/**结束会话*/
export const endDialog = (self, tiyData) => {
  let params = {userId: self.userId};
  self.$Spin.show();
  self.$apiChat.endChat(params).then(response => {
      self.$Spin.hide();
      if(response.success) {
        self.$emit("hideDetail");
        self.$emit("refreshList");
      }else{
        self.$Message.error(response.errorMessage);
      }
  });
};

/**
 * 初始化展厅查询参数
 * @param self
 */
export const initQueryShowroom = (self) => {
  showroomData.tParam.title = "";
  showroomData.tParam.name = "";
  showroomData.tParam.type = null;
  showroomData.tParam.state = null;
  showroomData.tParam.platform = "";
  showroomData.tParam.tag = "";
  //选中数据
  showroomData.tData.selectedId = "";
  self.$ySpliceAll(showroomData.tData.selectedList);

  showroomData.tPage.total = 0;
  showroomData.tPage.pageNum = 1;
  showroomData.tPage.pageSize = 40;
  showroomData.tPage.options.splice(0);
}

/**查询展厅列表*/
export const queryShowroomList = (self, tiyData) => {
  let params = showroomData.tParam;
  params.pageNum = showroomData.tPage.pageNum;
  params.pageSize = showroomData.tPage.pageSize;
  self.$ySpliceAll(showroomData.tData.list);
  self.$Spin.show();
  self.$apiStand.queryStandsList(params).then(response => {
    if(response.success) {
      let page = response.result;
      showroomData.tData.list.push(...page.list);
      showroomData.tPage.total = page.total;
    }else{
      showroomData.tPage.total = 0;
      self.$Message.error(response.errorMessage);
    }
    self.$Spin.hide();
  });
};

/**发送展厅消息*/
export const sendShowroomData = (self, tiyData) => {
  if(showroomData.tData.selectedList.length == 0) {
    self.$Message.error("请选择展厅！");
    return;
  }
  let showroom = showroomData.tData.selectedList[0];
  let sendShowroom = {};
  sendShowroom.standRoomId = showroom.id;
  sendShowroom.standRoomTitle = showroom.title;
  // sendShowroom.standRoomImg = showroom.id;
  sendShowroom.standRoomUrl = showroom.shortLink;
  sendShowroom.standRoomSubTitle = showroom.subtitle;
  sendShowroom.standRoomPlatform = showroom.platform;

  tiyData.tParams.messageSendParam.content = JSON.stringify(sendShowroom);
  tiyData.tParams.messageSendParam.type = 800;

  chatSendMessage(self, tiyData);
}

export const queryProductSupplyList = (self, tiyData, cartProduct) => {
  self.$Spin.show();
  let params = {productId: cartProduct.productId};
  self.$apiProduct.getProductSupplys(params).then(response => {
    self.$Spin.hide();
    tiyData.tData.productSupplyList.splice(0);
    if(response.success) {
      tiyData.tData.productSupplyList.push(...response.result);
    }else{
      console.error(response);
      self.$Message.error(response.errorMessage);
    }
  }).catch(() => {
    self.$Spin.hide();
    self.$Message.error("查询产品货源失败！");
  });
}

export const saveUserContactEmail = (self, tiyData) => {
  self.$refs.emailForm.validate(valid => {
    if(valid) {
      let params = tiyData.tParams.userEmailParam;
      self.$Spin.show();
      self.$apiChat.saveUserContactEmail(params).then(response => {
        self.$Spin.hide();
        if(response.success) {
          tiyData.tStatus.modalEmail.isShow = false;
          self.$Message.success("保存成功！");
          getUserContactEmail(self, tiyData);
        }else{
          console.error(response);
          self.$Message.error(response.errorMessage);
        }
      }).catch(() => {
        self.$Spin.hide();
        self.$Message.error("保存失败！");
      });
    }else{
      console.error("validate failed");
    }
  })
}

export const getUserContactEmail = (self, tiyData) => {
  let params = {userId: self.userId};
  self.$Spin.show();
  self.$apiChat.getUserContactEmail(params).then(response => {
    self.$Spin.hide();
    tiyData.tData.userEmail.id = "";
    tiyData.tData.userEmail.userId = "";
    tiyData.tData.userEmail.email = "";
    tiyData.tData.userEmail.note = "";
    tiyData.tData.userEmail.createtime = null;
    if(response.success) {
      if(response.result != null) {
        tiyData.tData.userEmail = response.result;
      }
    }else{
      console.error(response);
      self.$Message.error(response.errorMessage);
    }
  }).catch(() => {
    self.$Spin.hide();
    self.$Message.error("查询用户联系邮箱失败！");
  });
}
